package anc.server.tankshooter.network;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import anc.server.tankshooter.App;
import anc.server.tankshooter.models.Account;

/**
 * Chứa các hàm static để gởi và nhận gói tin
 * @author WolfNguyen
 *
 */
public class IOStream {

	public static DataPacket ReadPacket(DataInputStream dis) throws IOException
	{
		int command = dis.readInt();
		int length = dis.readInt();
		byte[] bytes = new byte[length];
		dis.read(bytes);
		DataPacket pk = new DataPacket(command, bytes) ;
		App.printCommand(pk);
		return pk;
	}
	
	public static boolean Send(int command, String s, DataOutputStream dos)
	{
		return SendPacket(new DataPacket(command, s), dos);
	}
	
	public static boolean SendPacket(DataPacket packet, DataOutputStream dos)
	{
		try{
			dos.writeInt(packet.getCommand());
			dos.writeInt(packet.getValueLength());
			dos.write(packet.getBytes());
			dos.flush();
			return true;
		}catch(IOException e)
		{
			return false;
		}
	}
	
	public static boolean SendInfo(Account account, DataOutputStream dos)
	{
		String value = String.format("%d:%d:%s:%s:%d", account.getAccountId(), account.getAvatarId(), account.getName(), account.getEmail(), account.getLevel());
		try {
			dos.writeInt(CommandList.SERVER_LOGIN_SUCCESSED);
			dos.writeInt(value.getBytes().length);
			dos.write(value.getBytes());
			dos.flush();
			return true;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			return false;
		}
	}
	
	public static boolean LoginFailed(DataOutputStream dos, int type)
	{
		try {
			dos.writeInt(CommandList.SERVER_LOGIN_FAILED);
			String theValue = String.valueOf(type);
			dos.writeInt(theValue.getBytes().length);
			dos.write(theValue.getBytes());
			dos.flush();
			return true;
		} catch (IOException e) {
			return false;
		}
	}
}
